package com.example.blog.controller;

import com.example.blog.model.BlogInfo;
import com.example.blog.model.Result;
import com.example.blog.service.BlogService;
import com.example.blog.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * ClassName: BlogController
 * Package: IntelliJ IDEA
 * Description:
 *
 * @Author 谷京京
 * @Create 2024/3/26 10:29
 * @Version 1.0
 */
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;

    /**
     * 获取博客列表
     * @return
     */
    @RequestMapping("/getList")
    public List<BlogInfo>  getBlogList() {
        return blogService.setBlogList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer id, HttpServletRequest request) {
        BlogInfo blogInfo = blogService.getBlogDetail(id);
        //判断作者是否未登录用户
        Integer editor = blogInfo.getUserId();
        String token = request.getHeader("user_token");
        Integer userId = JwtUtil.getUserIdFromToken(token);
        blogInfo.setLoginUser(userId != null && Objects.equals(userId, editor));
        return blogInfo;
    }
    @RequestMapping("/add")
    public Result publishBlog(String title, String content, HttpServletRequest request) {
        //从token中获取userId
        String token = request.getHeader("user_token");
        Integer userId = JwtUtil.getUserIdFromToken(token);
        if(userId == null || userId < 0) {
            return Result.fail("用户未登录", false);
        }
        BlogInfo blog = new BlogInfo();
        blog.setUserId(userId);
        blog.setTitle(title);
        blog.setContent(content);
        blogService.insertBlog(blog);
        return Result.success(true);
    }
    @RequestMapping("/update")
    public boolean updateBlog(String title, String content, Integer id) {
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setId(id);
        blogService.updateBlog(blogInfo);
        return true;
    }
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer id) {
        blogService.delete(id);
        return true;
    }
}
